//
//  HWHomeViewController.swift
//  HWanGame
//
//  Created by 王昌健 on 2021/12/23.
//  Copyright © 2021 94Wan. All rights reserved.
//

import UIKit
import JXSegmentedView
import swiftScan
import Stevia


class HWHomeViewController: HWBaseViewController {
    
    /// 消息
    var messageButton = c_make_ex(UIButton.self)
        .image("homeMessageButton").image("homeMessageSel", state: .selected).end()
    private let scanButton = c_make_ex(UIButton.self)
        .image("Home_scan").end()
    private let searchButton = c_make_ex(UIButton.self)
        .image("Home_search").end()
    /// 刷新数据
    var refreshButton:UIButton!
    ///标签
    var segmentedView: JXSegmentedView = JXSegmentedView(frame: CGRect.zero)
    var segmentedDataSource: JXSegmentedTitleDataSource!
    var listContainerView: JXSegmentedListContainerView!
    var httpManager = HWHomeHttpManager()
    var titles:[String] = Array()
    var tagModel:HWHomeConfigModel = HWHomeConfigModel()
    var mineHttpManager = HWMineHttpManager()
    override func viewDidLoad() {
        super.viewDidLoad()
        
        initUI()
        
        initFrame()
        
        loadData()
        
        getHomeAlert()
        
        let firstVC = HWFirstPageViewController()
        firstVC.banbenqueryUpdateversion()
        
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        if HWLocallyStoredData.getLoginUserID().count>0{
            loadMessageInfo()
        }
    }
    
    deinit {
        NotificationCenter.default.removeObserver(self)
    }
}

extension HWHomeViewController {
    private func initUI() -> Void {
        
        navigationView.isHidden = true
        view.backgroundColor = .colorWithHexString(hexString: "#F7F8FA")
    
        
        view.subviews{
            scanButton
            searchButton
            messageButton
            segmentedView
        }
        
        searchButton.addTarget(self, action: #selector(searchButtonClick), for: .touchUpInside)
        scanButton.addTarget(self, action: #selector(scanButtonClick), for: .touchUpInside)
        messageButton.addTarget(self, action: #selector(messageButtonClick(_:)), for: .touchUpInside)
                
        segmentedDataSource = JXSegmentedTitleDataSource()
        segmentedDataSource.titles = []
        
        segmentedDataSource.isTitleColorGradientEnabled = true
        segmentedDataSource.titleNormalColor = UIColor.colorWithHexString(hexString: "#47494D")
        segmentedDataSource.titleSelectedColor = UIColor.colorWithHexString(hexString: "#17181A")
        segmentedDataSource.titleNormalFont = .systemFont(ofSize: 16*widthScale, weight: .regular)
        segmentedDataSource.titleSelectedFont = .systemFont(ofSize: 16*widthScale, weight: .semibold)
        segmentedDataSource.itemSpacing = 11*widthScale
        segmentedView.dataSource = segmentedDataSource
        
        let indicator = JXSegmentedIndicatorImageView()
        indicator.image = "segement_dian".toImage
        indicator.indicatorWidth = 13*widthScale
        indicator.indicatorHeight = 13*widthScale
//        indicator.verticalOffset = 10*widthScale
        segmentedView.indicators = [indicator]
        
        segmentedView.delegate = self
        segmentedView.backgroundColor = .clear
//        view.addSubview(self.segmentedView)
        
        
        listContainerView = JXSegmentedListContainerView(dataSource: self)
        view.addSubview(listContainerView)
        
        segmentedView.listContainer = listContainerView
        
        refreshButton = UIButton(type: .custom)
        refreshButton.frame = CGRect(x: 0, y: 0, width:100*widthScale, height: 40*widthScale)
        refreshButton.setTitle("点击重试", for: .normal)
        refreshButton.setTitleColor(.white, for: .normal)
        refreshButton.titleLabel?.font = .boldSystemFont(ofSize: 14*widthScale)
        refreshButton.layer.cornerRadius = 20*widthScale
        refreshButton.layer.masksToBounds = true
        refreshButton.addTarget(self, action: #selector(refreshButtonClick(_:)), for: .touchUpInside)
        UIColor.gradientColor(view: refreshButton, colors: [UIColor.colorWithHexString(hexString: "#FFB60A").cgColor,UIColor.colorWithHexString(hexString: "#F66A05").cgColor], start: CGPoint(x: 0, y: 0), end: CGPoint(x: 1, y: 0))
        view.addSubview(refreshButton)
        refreshButton.isHidden = true
        
        NotificationCenter.default.addObserver(self, selector: #selector(toRankListVC), name: .toAllRankListVC, object: nil)
    }
    
    private func initFrame() -> Void {
        
        segmentedView.leading(0).top(CGFloat.statusHeight).height(44*widthScale).trailing(105)
        messageButton.trailing(12*widthScale).size(24*widthScale)
        messageButton.CenterY == segmentedView.CenterY
        scanButton.trailing(44*widthScale).size(24*widthScale)
        scanButton.CenterY == segmentedView.CenterY
        searchButton.trailing(76*widthScale).size(24*widthScale)
        searchButton.CenterY == segmentedView.CenterY
        
        listContainerView.snp.makeConstraints { make in
            make.left.right.equalToSuperview()
            make.top.equalTo(segmentedView.snp.bottom)
            make.bottom.equalTo(self.view.safeAreaLayoutGuide.snp.bottom)
        }
        
        refreshButton.snp.makeConstraints { make in
            make.center.equalToSuperview()
            make.width.equalTo(100*widthScale)
            make.height.equalTo(40*widthScale)
        }
    }
}
extension HWHomeViewController:JXSegmentedListContainerViewDataSource,JXSegmentedViewDelegate {
    func numberOfLists(in listContainerView: JXSegmentedListContainerView) -> Int {
        return segmentedDataSource.dataSource.count
    }
    
    func listContainerView(_ listContainerView: JXSegmentedListContainerView, initListAt index: Int) -> JXSegmentedListContainerViewListDelegate {
        let type = self.tagModel.index_top[index].type
        if type == "1" {
            return HWHomeNewRecommendViewController()
        }else if type == "5" {
            return HWRankListViewController()
        }else if type == "2" {
            return HWGameClassifyController()
        }else if type == "11" {
            
            let wukongVC = HWWuKongViewController()
            wukongVC.gid = self.tagModel.index_top[index].gid
            return HWWuKongViewController()
        }else{
//            let recommendVC = HWHomeRecommendController()
            let normalVC = HWHomeNormalController()
            normalVC.type = self.tagModel.index_top[index].type
            return normalVC
        }
    }
    
    func segmentedView(_ segmentedView: JXSegmentedView, didSelectedItemAt index: Int) {
        
    }
}

extension HWHomeViewController {
    func loadData() -> Void {
        
        httpManager.getHomeConfig { model in
            self.refreshButton.isHidden = true
            self.tagModel.index_top.removeAll()
            self.titles.removeAll()
            for mod in model.index_top {
                if mod.status == true {
                    self.titles.append(mod.name)
                    self.tagModel.index_top.append(mod)
                }
            }
            self.segmentedDataSource.titles = self.titles
            self.segmentedView.reloadData()
            
            if model.shiwan_appid.count > 0 {
                DyAdApi.register(withMediaId: model.shiwan_appid, appKey: model.shiwan_key)
            }
            
        } failure: { error in
            self.refreshButton.isHidden = false
        }
    }
    ///查看是否有新消息
    func loadMessageInfo() -> Void {
        mineHttpManager.getMineNewMessageInfo { show in
            self.messageButton.isSelected = true
        } failure: { error in
            self.messageButton.isSelected = false
        }
    }
    
    func getHomeAlert() -> Void {
        httpManager.getHomeAlert { model in
            if model.status == true {
                let gameAlert = HWHomeGameAlert(frame: .zero)
                gameAlert.model = model
                gameAlert.show()
                gameAlert.gameButtonClick = {
                    id in
                    let gameDetail = HWGameDetailController()
                    gameDetail.gameId = id
                    self.navigationController?.pushViewController(gameDetail, animated: true)
                }
            }
        } failure: { error in
            
        }
        
    }
}

extension HWHomeViewController {
    @objc func searchButtonClick() -> Void {
        let searchController = HWSearchController()
        searchController.modalPresentationStyle = .overFullScreen
        self.present(searchController, animated: true, completion: nil)
    }
    
    @objc func messageButtonClick(_ :UIButton) -> Void {
        if HWLocallyStoredData.getLoginUserID().count>0{
            let message = HWXiaoXiMessageCenterViewController()
            self.navigationController?.pushViewController(message, animated: true)
        }else {
            let loginController = HWLoginController()
            self.navigationController?.pushViewController(loginController, animated: true)
        }
    }
    
    @objc private func scanButtonClick(){
        if HWLocallyStoredData.getLoginUserID().count>0{
            //设置扫码区域参数
            var style = LBXScanViewStyle()
            style.centerUpOffset = 44
            style.photoframeAngleStyle = LBXScanViewPhotoframeAngleStyle.Inner
            style.photoframeLineW = 2
            style.photoframeAngleW = 18
            style.photoframeAngleH = 18
            style.isNeedShowRetangle = false

            style.anmiationStyle = LBXScanViewAnimationStyle.LineMove

            style.colorAngle = UIColor(red: 0.0/255, green: 200.0/255.0, blue: 20.0/255.0, alpha: 1.0)

            style.animationImage = UIImage(named: "qrcode_Scan_weixin_Line")

            let vc = HWScanViewController()
            vc.scanStyle = style
            vc.readyString = "加载中"
            vc.scanResultDelegate = self
            let v = UIView()
            v.frame = CGRect(x: 0, y: 0, width: 100, height: 100)
            v.backgroundColor = .red
            
            self.navigationController?.pushViewController(vc, animated: true)
            vc.qRScanView?.addSubview(v)
        }else {
            let loginController = HWLoginController()
            self.navigationController?.pushViewController(loginController, animated: true)
        }
    }
        
    @objc func tapHeadImage(_ :UITapGestureRecognizer) -> Void {
        self.tabBarController?.selectedIndex = 4
    }
    
    @objc func refreshButtonClick(_:UIButton) -> Void {
        loadData()
    }
    
    @objc private func toRankListVC(){
        self.segmentedView.selectItemAt(index: 1)
    }
}

extension HWHomeViewController: LBXScanViewControllerDelegate {
    func scanFinished(scanResult: LBXScanResult, error: String?) {
        
        DispatchQueue.main.asyncAfter(deadline: .now() + .milliseconds(400)) {
            if scanResult.strScanned?.hasPrefix("LoginToken") == true {
                let vc = HWScanLoginController()
                vc.strScanned = scanResult.strScanned ?? ""
                self.navigationController?.pushViewController(vc, animated: true)
            } else if scanResult.strScanned?.hasPrefix("http") == true{
                let url = URL(string: scanResult.strScanned ?? "")
                if url != nil {
                    UIApplication.shared.open(url!)
                } else {
                    self.view.showHUD(title: "二维码无效")
                }
            } else {
                self.view.showHUD(title: "二维码无效")
            }
        }
    }
    
}

